package com.lanou3g.musicenjoy.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou3g.musicenjoy.activities.HelloDrawerActivity;
import com.lanou3g.musicenjoy.entity.PlayMusicEntity;
import com.lanou3g.musicenjoy.entity.Song;
import com.lanou3g.musicenjoy.entity.greendao.MusicInfoBean;
import com.lanou3g.musicenjoy.entity.greendao.MusicInfoBeanDao;
import com.lanou3g.musicenjoy.eventbus.MyEvent;
import com.lanou3g.musicenjoy.R;
import com.lanou3g.musicenjoy.entity.SearchSingleSong;
import com.lanou3g.musicenjoy.greendao.DaoSingleton;
import com.lanou3g.musicenjoy.service.OnlineService;
import com.squareup.picasso.Picasso;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.dao.query.DeleteQuery;
import de.greenrobot.dao.query.QueryBuilder;
import de.greenrobot.event.EventBus;


/**
 * Created by 辛鑫 on 15/10/21.
 */
public class SearchingSingleSongAdapter extends BaseExpandableListAdapter {

    //group的内容
    private List<SearchSingleSong.DataEntity> data;
    private Context mContext;
    private String[] quality;
    private PlayMusicEntity playEntity;
    private List<PlayMusicEntity> musicEntities;
    private List<Song> datas;
   // private HelloDrawerActivity activity;

//    public SearchingSingleSongAdapter(Context mContext) {
//        this.mContext = mContext;
//        activity = (HelloDrawerActivity) mContext;

    //李宁收藏
    private MusicInfoBean info;//实体类
    private ArrayList<MusicInfoBean> infos;
    private QueryBuilder<MusicInfoBean> queryBuilder;
    private MusicInfoBeanDao musicInfoBeanDao;//表
    private DaoSingleton daoSingleton;
    private OnlineService.MediaBinder mediaBinder;//查询数据库表用




    public SearchingSingleSongAdapter(Context mContext) {
        this.mContext = mContext;
        //李宁 dao初始化
        daoSingleton = DaoSingleton.getInstance();
        musicInfoBeanDao = daoSingleton.getMusicInfoBeanDao();
        queryBuilder = musicInfoBeanDao.queryBuilder();

    }

    //更新数据
    public void setDatas(List<SearchSingleSong.DataEntity> data) {
        this.data = data;

        notifyDataSetChanged();
    }

    //child
    @Override
    public int getChildrenCount(int groupPosition) {
        return 1;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return null;
    }


    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        Log.i("绘制", groupPosition + "");
        ViewHolderOne holderOne = null;
        convertView = LayoutInflater.from(mContext).inflate(R.layout.singlesong_content_child, null);
        holderOne = new ViewHolderOne(convertView);
        final List<SearchSingleSong.DataEntity.AuditionListEntity> entity = data.get(groupPosition).getAuditionList();
        //对播放进行监听
        holderOne.musicPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("位置", groupPosition + "00000");
                musicEntities = new ArrayList<PlayMusicEntity>();
//                if (data.get(groupPosition).getAuditionList().size() > 0) {
//                    Toast.makeText(mContext, "正在为您准备歌曲", Toast.LENGTH_SHORT).show();
//                    //发布
//                    EventBus.getDefault().post(new MyEvent.PassData(data, 1, groupPosition));
//
//                } else {
//                    Toast.makeText(mContext, "由于版权问题,当前音乐无法播放.", Toast.LENGTH_SHORT).show();
//                }
                if (data.get(groupPosition).getAuditionList().size() > 0) {

                    for (SearchSingleSong.DataEntity dataEntity : data) {
                        playEntity = new PlayMusicEntity();
                        if (dataEntity.getAuditionList().size() > 0 ) {
                            Log.i("adapter", dataEntity.getSingerName());
                            Log.i("adapter", dataEntity.getAuditionList().get(0).getUrl());
                            playEntity.setSingerName(dataEntity.getSingerName());
                            playEntity.setSongName(dataEntity.getName());
                            playEntity.setUrl(dataEntity.getAuditionList().get(0).getUrl());

                            if (dataEntity.getMvList().size() > 0) {
                                playEntity.setPicUrl(dataEntity.getMvList().get(0).getPicUrl());
                            }

                            musicEntities.add(playEntity);

                        }

                    }

                    EventBus.getDefault().post(new MyEvent.PassData(musicEntities, groupPosition));

                } else {

                    Toast.makeText(mContext, "由于版权问题,当前音乐无法播放", Toast.LENGTH_SHORT).show();
                }

            }
        });
        //对收藏进行监听
        holderOne.musicCollection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //设置数据
                info = new MusicInfoBean();
                info.setSongname(data.get(groupPosition).getName());
                info.setSinger(data.get(groupPosition).getSingerName());
//                Toast.makeText(mContext, "点击了收藏", Toast.LENGTH_SHORT).show();
                //李宁
                infos = (ArrayList<MusicInfoBean>) queryBuilder.where(MusicInfoBeanDao.Properties.Songname.eq(data.get(groupPosition).getName())).list();
                Log.i("liningggg", infos + "is");
                if (data.get(groupPosition).getAuditionList().size() <= 0){
                    Toast.makeText(mContext, "当前无音乐", Toast.LENGTH_SHORT).show();
                }else {
                    if (infos == null || infos.size() == 0) {
                        MusicInfoBean musicInfoBean = new MusicInfoBean();
                        musicInfoBean = info;
                        Log.i("musicInfoBean", musicInfoBean + "");
                        musicInfoBean.setSongname(data.get(groupPosition).getName());
                        musicInfoBeanDao.insert(musicInfoBean);
                        Log.i("xxx", musicInfoBean.getSongname());
                        Toast.makeText(mContext, "收藏成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(mContext, "取消收藏", Toast.LENGTH_SHORT).show();
                        DeleteQuery<MusicInfoBean> deleteQuery = queryBuilder.where(MusicInfoBeanDao.Properties.Songname.eq(data.get(groupPosition).getName())).buildDelete();
                        deleteQuery.executeDeleteWithoutDetachingEntities();
                    }
                }
            }
        });
        //对下载进行监听
        holderOne.musicDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DownloadDialog(groupPosition);
            }
        });
        //对分享进行监听
        holderOne.musicEnjoy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "点击了分享", Toast.LENGTH_SHORT).show();
                // 首先在您的Activity中添加如下成员变量
                final UMSocialService mController = UMServiceFactory.getUMSocialService("http://www.liwushuo.com/credit/invitation?code=tp23io");
                // 设置分享内容
                mController.setShareContent("邀请你一起共享音乐");
                // 设置分享图片, 参数2为图片的url地址
            //    Log.i("fjjjjj", data.get(groupPosition).getAuditionList().get(childPosition).getUrl());
                mController.setShareMedia(new UMImage(mContext,data.get(groupPosition%data.size()).getAuditionList().get(childPosition%data.size()).getUrl()
                        ));
                mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);

                //参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
                UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler((Activity)mContext, "100424468",
                        "c7394704798a158208a74ab60104f0ba");
                qqSsoHandler.addToSocialSDK();

                //参数1为当前Activity，参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
                QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler((Activity)mContext, "100424468",
                        "c7394704798a158208a74ab60104f0ba");
                qZoneSsoHandler.addToSocialSDK();
                mController.openShare((Activity)mContext, false);
                //新浪分享
                mController.getConfig().setSsoHandler(new SinaSsoHandler());
            }
        });
        return convertView;
    }

    //group
    @Override
    public int getGroupCount() {
        return data != null && data.size() > 0 ? data.size() : 0;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return data != null && data.size() > 0 ? data.get(groupPosition) : null;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.singlesong_content, null);
            holder = new ViewHolder();
            holder.songListTime = (TextView) convertView.findViewById(R.id.song_list_time);
            holder.songTitle = (TextView) convertView.findViewById(R.id.song_title);

            holder.songSinger = (TextView) convertView.findViewById(R.id.song_singer);

            holder.heart = (ImageView) convertView.findViewById(R.id.header);

            holder.songFivortNum = (TextView) convertView.findViewById(R.id.song_fivort_num);

            holder.expandImg = (ImageView) convertView.findViewById(R.id.expand_img);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        SearchSingleSong.DataEntity dataEntity = (SearchSingleSong.DataEntity) getGroup(groupPosition);

        if (dataEntity != null) {
            holder.songTitle.setText(dataEntity.getName());
            holder.songFivortNum.setText(dataEntity.getFavorites() + "");
            holder.songSinger.setText(dataEntity.getSingerName());
            holder.songListTime.setText(groupPosition + 1 + "");
        }

        return convertView;
    }

    //当列表收缩时会调用的方法
    @Override
    public void onGroupCollapsed(int groupPosition) {
        super.onGroupCollapsed(groupPosition);
       // Picasso.with(mContext).load(R.mipmap.img_right_menu_arrow_down).into(holder.getExpandImg());
        Log.i("111", "收缩为重" + groupPosition);
        Log.i("000", "列表关闭");
    }

    //当列表展开时会调用的方法
    @Override
    public void onGroupExpanded(int groupPosition) {
        super.onGroupExpanded(groupPosition);
        //Picasso.with(mContext).load(R.mipmap.img_right_menu_arrow_up).into(holder.getExpandImg());
        Log.i("111", "展开位置" + groupPosition);
        Log.i("000", "列表展开");
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }


    /**
     * This class contains all butterknife-injected Views & Layouts from layout file 'singlesong_content_child.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
     */

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file 'singlesong_content_child.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
     */

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file 'singlesong_content.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
     */
    static class ViewHolder {
        TextView songListTime;
        TextView songTitle;
        TextView songSinger;
        ImageView heart;
        TextView songFivortNum;
        ImageView expandImg;

        public ImageView getExpandImg() {
            return expandImg;
        }
    }


    static class ViewHolderOne {
        @Bind(R.id.music_download)
        TextView musicDownload;
        @Bind(R.id.music_enjoy)
        TextView musicEnjoy;
        @Bind(R.id.music_collection)
        TextView musicCollection;
        @Bind(R.id.music_play)
        TextView musicPlay;

        ViewHolderOne(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 点击下载弹出对话框
     */
    private void DownloadDialog(final int position) {
        final List<SearchSingleSong.DataEntity.AuditionListEntity> entity = data.get(position).getAuditionList();
        //数组初始化时一定要定义它的长度
        quality = new String[entity.size()];
        //获取小数点后两位的方法
        DecimalFormat df = new DecimalFormat("0.00");
        for (int i = 0; i < entity.size(); i++) {
            String str = entity.get(i).getTypeDescription();
            double size = entity.get(i).getSize();
            quality[i] = str + df.format(size / 1024000) + "M";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("请选择下载品质");
        builder.setItems(quality, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(mContext, entity.get(which).getTypeDescription() + "已加入到下载列表中", Toast.LENGTH_SHORT).show();
                String url = entity.get(which).getUrl();
                String singerName = data.get(position).getSingerName();
                String title = data.get(position).getName();
                String picUrl = "";
                if (data.get(position).getMvList().size() > 0) {
                    Log.i("qqqq", which + "000");
                    picUrl = data.get(position).getMvList().get(0).getPicUrl();
                }
                    EventBus.getDefault().post(new MyEvent.DownlaodData(picUrl, title, url));


            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).show();
    }

}
